/*
  学习目标：实现点谁谁高亮
  步骤：

*/

import {
  addChannelAPI,
  delChannelByIdAPI,
  getAllChannelsAPI,
  getUserChannelsAPI,
} from '@/api/channel';
import store, { AppDispatch } from '..';
import { Toast } from 'antd-mobile';
import { getLocalChannels, hasToken, setLocalChannels } from '@/utils/storage';
import { ActionType, IChannel } from '../reducer/channel';
export const getAllChannelsAction = () => {
  return async (dispatch: AppDispatch) => {
    const res = await getAllChannelsAPI();
    dispatch({ type: 'channel/saveList', payload: res.data.channels });
  };
};

export const getUserChannelsAction = () => {
  return async (dispatch: AppDispatch) => {
    if (hasToken()) {
      const res = await getUserChannelsAPI();
      dispatch({ type: 'channel/saveUserList', payload: res.data.channels });
      return;
    }

    const localUserList = getLocalChannels();
    if (!localUserList.length) {
      const res = await getAllChannelsAPI();
      const list = res.data.channels.slice(0, 10);
      dispatch({ type: 'channel/saveUserList', payload: list });
      setLocalChannels(list);
      return;
    }

    dispatch({ type: 'channel/saveUserList', payload: localUserList });
  };
};

export const delChannelByIdAction = (id: number) => {
  return async (dispatch: AppDispatch, getState: typeof store.getState) => {
    const { userList } = getState().channel;

    if (userList.length < 5) {
      Toast.show({ content: '至少保留5个频道', icon: 'warning' });
      return;
    }

    if (id === 0) {
      Toast.show({ content: '不允许删除推荐', icon: 'warning' });
      return;
    }

    if (hasToken()) {
      await delChannelByIdAPI(id);
    } else {
      let localUserList = getLocalChannels();
      localUserList = localUserList.filter((item) => item.id !== id);
      setLocalChannels(localUserList);
    }

    dispatch({ type: 'channel/delById', payload: id });
    Toast.show({ content: '删除成功', icon: 'success' });
  };
};

export const addChannelAction = (id: number) => {
  return async (dispatch: AppDispatch, getState: typeof store.getState) => {
    if (hasToken()) {
      await addChannelAPI(id);
    } else {
      let localUserList = getLocalChannels();
      const { allList } = getState().channel;
      const newItem = allList.find((item) => item.id === id);
      console.log('newItem  ----->  ', newItem);
      setLocalChannels([...localUserList, newItem as IChannel]);
    }

    dispatch({ type: 'channel/addById', payload: id });
    Toast.show({ content: '添加成功', icon: 'success' });
  };
};

// 3. 封装同步的Action
export const setCurrentIdAction = (id: number): ActionType => ({
  type: 'channel/setId',
  payload: id,
});
